<template> 
  <div class="rolling-numbers">
    <div
      v-for="(num, index) in displayCount"
      :key="index"
      class="number-wrapper"
    >
      <div
        class="number"
        :class="{ rolling: isActive }"
      >
        {{ currentNumbers[index] }}
      </div>
    </div>
    <div v-if="isEllipsis" class="ellipsis">...</div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted } from 'vue';

const props = defineProps({
  count: {
    type: Number,
    required: true
  },
  maxDisplay: {
    type: Number,
    default: 9
  },
  active: {
    type: Boolean,
    default: true
  },
  maxNumber: { 
    type: Number,
    required: true
  }
});

const displayCount = ref(Math.min(props.count, props.maxDisplay));
const isEllipsis = ref(props.count > props.maxDisplay);
const currentNumbers = ref(Array(displayCount.value).fill(Math.floor(Math.random() * props.maxNumber) + 1));
const isActive = ref(props.active);

let intervalId = null;

const startRolling = () => {
  intervalId = setInterval(() => {
    currentNumbers.value = currentNumbers.value.map(() => {
      return Math.floor(Math.random() * props.maxNumber) + 1; 
    });
  }, 100);
};

const stopRolling = () => {
  clearInterval(intervalId);
  intervalId = null;
};

watch(() => props.active, (newVal) => {
  isActive.value = newVal;
  if (newVal) {
    startRolling();
  } else {
    stopRolling();
  }
});

onMounted(() => {
  if (isActive.value) {
    startRolling();
  }
});

onUnmounted(() => {
  stopRolling();
});
</script>

<style scoped>
.rolling-numbers {
  display: flex;
  align-items: center;
}

.number-wrapper {
  min-width: 3em; 
  height: 2em;
  margin: 0 0.2em;
  display: flex;
  align-items: center;
  justify-content: center;
}

.number {
  font-size: 1.5em;
  transition: transform 0.1s ease-in-out;
  text-align: center;
}

.ellipsis {
  font-size: 1.5em;
  margin-left: 0.5em;
}

</style>
